package com.core.controller;

import java.util.List;
import java.util.Map;

import com.core.entity.Condition;
import com.core.entity.JsonPage;
import com.core.utils.R;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

public class BaseController<T> extends Controller {
	
	private Integer page = new Integer(1);//页码 PageNo
	private Integer rows = new Integer(10);//页数 PageSize
	
	/**
	 * datagrid 页码
	 */
	public Integer getPageNo() {
		if(getPara("page") == null || "".equals(getPara("page")))
			return page;
		return getParaToInt("page");
	}
	
	/**
	 * datagrid 页数
	 */
	public Integer getPageSize() {
		if ((getPara("rows") == null) || ("".equals(getPara("rows"))))
			return rows;
		return getParaToInt("rows");
	}
	
	/**
	 * jsp 页码
	 */
	public Integer getPageNo4Url() {
		if(getPara(0) == null || "".equals(getPara(0)))
			return page;
		return getParaToInt(0);
	}
	
	/**
	 * jsp 页数
	 */
	public Integer getPageSize4Url() {
		if ((getPara(1) == null) || ("".equals(getPara(1))))
			return rows;
		return getParaToInt(1);
	}
	
	public void renderJsonPage(Page<T> page) {
		super.renderJson(new JsonPage<T>(page));
	}
	
	public Map<String, Object> jsonMap(boolean result){
		Map<String, Object> resultMap = Maps.newHashMap();//可以继续添加属性
		resultMap.put(R.Key_IsSuccess, result);
		resultMap.put(R.Key_Msg, result ? R.Msg.SAVE_SUCCESS : R.Msg.SAVE_FAILURE);
		return resultMap;
	}

	/**
	 * 绑定查询参数
	 */
	protected List<Condition> bindConditions() {
		List<Condition> conditions = Lists.newArrayList();
		Map<String, String[]> map = getRequest().getParameterMap();
		for (String key : map.keySet()) {
			if (StrKit.notBlank(key)) {
				String value = map.get(key)[0];
				if(StrKit.isBlank(value)){
					continue;
				}
				if ("page".equalsIgnoreCase(key)) {
					continue;
				}
				if ("rows".equalsIgnoreCase(key)) {
					continue;
				}
				if ("order".equalsIgnoreCase(key)) {
					continue;
				}
				if ("sort".equalsIgnoreCase(key)) {
					continue;
				}
				Condition condition = Condition.parseCondition(key);
				condition.setValue(value);
				conditions.add(condition);
				setAttr(key, value);
			}
		}
		return conditions;
	}
}
